﻿using Infra.CustomException;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication.Utils;

namespace WebApplication.Controllers
{
    public abstract class BaseController : Controller
    {
        protected readonly IDisposable _disposable;

        protected BaseController(IDisposable disposable)
        {
            this._disposable = disposable;
        }

        protected BaseController()
        { }

        protected virtual void ShowInfo(string message)
        {
            ViewBag.Info = message;
        }

        protected virtual void Successed(string message)
        {
            ViewBag.Success = message;
        }

        protected override void OnException(ExceptionContext filterContext)
        {
            filterContext.ExceptionHandled = true;

            if (filterContext.Exception is ControllerException)
            {
                var result = this.GetMessageFromException(filterContext.Exception);

                if (Request.IsAjaxRequest())
                    Response.Write(HtmlWriter.Create().GetWarningMessage(result));
                else
                    ViewBag.Warning = result;
            }
            else if (filterContext.Exception is DalException || filterContext.Exception is UtilException)
            {
                var result = this.GetMessageFromException(filterContext.Exception);

                if (Request.IsAjaxRequest())
                    Response.Write(HtmlWriter.Create().GetDangerMessage(result));
                else
                    ViewBag.Error = result;
            }
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (disposing && this._disposable != null)
                this._disposable.Dispose();
        }

        protected virtual string GetMessageFromException(Exception exception)
        {
            if (exception is IExceptionForShow)
                return (exception as IExceptionForShow).GetMessage(CultureInfo.CurrentUICulture);

            return exception.Message;
        }
    }
}